#include <Arduino.h>
#include "hub75e.h"
#include "analog_clock.h"
#include "clock_manager.h"
#include "espWifiCfg.h"
#include "ntpTime.h"
#include "display_config.h"

// 引脚定义 (保持原始顺序)
const uint8_t pins[14] = {13, 27, 5, 21, 22, 23, 25, 26, 14, 15, 16, 17, 18, 19};

Panel panel(DISPLAY_WIDTH, DISPLAY_HEIGHT, NUM_SCAN, pins);
EspWifiCfg wifiCfg;
NTPTime ntpTime;

// 状态变量
bool wifiConnected = false;
unsigned long lastTimeUpdate = 0;
unsigned long lastClockUpdate = 0;
unsigned long lastNTPAttempt = 0;
const unsigned long NTP_UPDATE_INTERVAL = 3600000;
const unsigned long CLOCK_UPDATE_INTERVAL = 1000;

// 绘制状态信息（使用 panel.width / panel.height，避免 relying on macros at runtime）
void drawStatusInfo() {
    uint16_t w = panel.width;
    uint16_t h = panel.height;
        // Do not clear the entire right half (because we draw a clock there).
        // Instead only clear small status areas on left and right so the clocks are preserved.
        const uint16_t indicatorSize = 5; // size of the small status squares
        uint16_t leftOriginX = 0;
        uint16_t rightOriginX = (panel.width > panel.height) ? (panel.width - panel.height) : 0;
        auto drawIndicatorsAt = [&](uint16_t originX) {
            // small connectivity indicator
            if (wifiConnected) {
                panel.fillRect(originX + 0, 0, originX + indicatorSize, indicatorSize, 0, 255, 0);
            } else {
                panel.fillRect(originX + 0, 0, originX + indicatorSize, indicatorSize, 255, 0, 0);
            }
            // status block below
            uint16_t statusBlockX0 = originX + 0;
            uint16_t statusBlockX1 = originX + indicatorSize;
            uint16_t statusBlockY0 = indicatorSize + 4;
            uint16_t statusBlockY1 = statusBlockY0 + indicatorSize;
            if (ntpTime.isTimeValid()) {
                panel.fillRect(statusBlockX0, statusBlockY0, statusBlockX1, statusBlockY1, 0, 0, 255);
            } else {
                panel.fillRect(statusBlockX0, statusBlockY0, statusBlockX1, statusBlockY1, 255, 255, 0);
            }
        };
        drawIndicatorsAt(leftOriginX);
        // Removed status indicators for right panel
}

void setup() {
    Serial.begin(115200);
    panel.begin();
    wifiCfg.begin();
    ntpTime.begin();
    // Keep system/local timezone as configured (default). We'll request the right panel time
    // explicitly for San Francisco when drawing.

    panel.clearScreen();
    Serial.println("ESP32 LED clock started");
}

void loop() {
    wifiCfg.loop();

    // 检查WiFi状态（封装到 EspWifiCfg）
    wifiCfg.updateWifiStatus(wifiConnected, lastNTPAttempt);

    // NTP时间同步（封装到 NTPTime）
    if (wifiConnected) {
        ntpTime.attemptSyncIfNeeded(lastNTPAttempt, 30000);
    }

    // 更新时钟显示（封装到 clock_manager）
    // Pass -8 to draw the right panel in San Francisco time
        // Update clock display (clock_manager will redraw both panels when needed)
        if (maybeUpdateClock(panel, ntpTime, lastClockUpdate, CLOCK_UPDATE_INTERVAL, -8)) {
            drawStatusInfo();
        }

    // 调试信息（每5秒打印一次）
    static unsigned long lastDebug = 0;
    if (millis() - lastDebug > 5000) {
        lastDebug = millis();
        if (ntpTime.isTimeValid()) {
            Serial.printf("Network time: %s\n", ntpTime.getFormattedTime().c_str());
        } else {
            unsigned long totalSeconds = millis() / 1000;
            uint8_t dbgSecond = totalSeconds % 60;
            uint8_t dbgMinute = (totalSeconds / 60) % 60;
            uint8_t dbgHour = (totalSeconds / 3600) % 24;
            Serial.printf("System time: %02d:%02d:%02d\n", dbgHour, dbgMinute, dbgSecond);
        }
    }

    delay(10);
}